-- LuaTools需要PROJECT和VERSION这两个信息
-- www.funiot.xyz
PROJECT = "led"
VERSION = "1.0.0"

-- 引入必要的库文件(lua编写), 内部库不需要require
sys = require("sys")

log.info("main", "led")

print(_VERSION)

if wdt then
    --添加硬狗防止程序卡死，在支持的设备上启用这个功能
    wdt.init(9000)--初始化watchdog设置为9s
    sys.timerLoopStart(wdt.feed, 3000)--3s喂一次狗
end
--用户代码开始---------------------------------------------------
--根据自己华为云物联网平台的配置修改以下参数，下列参数仅作参考
local mqtt_host = ""  --MQTT地址，例如iot-mqtts.cn-north-4.myhuaweicloud.com
local mqtt_port = 1883  
local mqtt_isssl = false
local client_id = ""    --MQTT Client ID
local user_name = ""    --MQTT Username
local password = ""     --MQTT password
local mqtt_hw = nil
local devdata_topic="$oc/devices/YOUR_DEV_ID/sys/properties/report" --订阅属性上报主题
local cmdrec_topic="$oc/devices/YOUR_DEV_ID/sys/commands/#"         --订阅命令下发主题
local service_id=""              --服务ID
local command_name=""            --控制命令
local LED_PIN=27                 --LED引脚编号
gpio.setup(LED_PIN,0, gpio.PULLUP)      --设置LED上拉输出

sys.taskInit(function()
    while 1 do
        --网络相关
        mobile.simid(2)
        LED = gpio.setup(27, 0, gpio.PULLUP)
        device_id = mobile.imei()
        sys.waitUntil("IP_READY", 30000)
        --mqtt客户端创建
        print("huawei iot\r\n");
        mqtt_hw = mqtt.create(nil,mqtt_host, mqtt_port, mqtt_isssl, ca_file)
        mqtt_hw:auth(client_id,user_name,password) 
        mqtt_hw:keepalive(60) -- 默认值240s
        mqtt_hw:autoreconn(true, 3000) -- 自动重连机制
        --注册mqtt回调
        mqtt_hw:on(function(mqtt_client, event, data, payload)
            -- 用户自定义代码
            log.info("mqtt", "event", event, mqtt_client, data, payload)
            if event == "conack" then   --连接响应成功
                sys.publish("mqtt_conack")--订阅主题
                mqtt_client:subscribe(devdata_topic)
                mqtt_client:subscribe(cmdrec_topic)
            elseif event == "recv" then
                log.info("mqtt", "downlink", "topic", data, "payload", payload)
                print("payload:",payload)
                --解析json
                --例如：{"paras":{"led":1},"service_id":"Dev_data","command_name":"Control"}
                local mycmd=json.decode(payload)
                if mycmd then -- 若解码失败, 会返回nil
                    print("service_id :",mycmd["service_id"])
                    print("command_name is",mycmd["command_name"])
                    print("paras->led is",mycmd["paras"]["led"])
                    if mycmd["service_id"]==service_id and mycmd["command_name"]==command_name then
                        if  mycmd["paras"]["led"]==1 then
                            print("led turn on")
                            gpio.set(LED_PIN, gpio.HIGH)
                        elseif mycmd["paras"]["led"]==0 then
                            print("led turn off")
                            gpio.set(LED_PIN, gpio.LOW)
                        end
                    end            
                end 
            elseif event == "sent" then
                log.info("mqtt", "sent", "pkgid", data)
            -- elseif event == "disconnect" then
                -- 非自动重连时,按需重启mqtt_hw
                -- mqtt_client:connect()
            end
        end)
        --连接mqtt
        mqtt_hw:connect()
        print("connect ok\r\n");
        sys.waitUntil("mqtt_conack")
        while true do
            -- mqtt_hw自动处理重连
            local ret, topic, data, qos = sys.waitUntil("mqtt_pub", 30000)
            if ret then
                if topic == "close" then break end
                mqtt_hw:publish(topic, data, qos)
            end
        end
        mqtt_hw:close()
        mqtt_hw = nil   
    end       
end)
--定时上报属性
sys.taskInit(function()
	local topic = devdata_topic --上报的topic
    local temp=0    --温度属性值
	local data = "{\"services\":[{\"service_id\":\"Dev_data\",\"properties\":{\"temp\": "..tostring(temp).."}}]}"
	local qos = 1
    local temp=0
    while true do
        sys.wait(5000)
        if mqtt_hw and mqtt_hw:ready() then
			-- mqtt_hw:subscribe(topic)
            local pkgid = mqtt_hw:publish(topic, data, qos)
            temp=temp+1
            data = "{\"services\":[{\"service_id\":\"Dev_data\",\"properties\":{\"temp\": "..tostring(temp).."}}]}"
            print("public ok\r\n");
            -- 也可以通过sys.publish发布到指定task去
            -- sys.publish("mqtt_pub", topic, data, qos)
        end
    end
end)

-- 用户代码已结束---------------------------------------------
-- 结尾总是这一句
sys.run()
-- sys.run()之后后面不要加任何语句!!!!!